<script setup>
import { ref } from "vue";

const props = defineProps({
  node: {
    type: Object,
    required: true,
  },
});

const emit = defineEmits(["fileClick"]); // 添加这行来定义emit

const isOpen = ref(false);

const toggleNode = () => {
  if (props.node.directory) {
    isOpen.value = !isOpen.value;
  } else {
    emit("fileClick", props.node); // 现在可以正确使用emit了
  }
};
</script>

<template>
  <div class="tree-item">
    <div class="tree-node" @click="toggleNode">
      <span class="node-icon">
        {{ node.directory ? (isOpen ? "📂" : "📁") : "📄" }}
      </span>
      <span class="node-name">{{ node.name }}</span>
    </div>
    <div
      v-if="node.children && node.children.length"
      class="tree-children"
      :class="{ 'tree-children-open': isOpen }"
    >
      <TreeNode
        v-for="child in node.children"
        :key="child.path"
        :node="child"
        @fileClick="$emit('fileClick', $event)"
      />
    </div>
  </div>
</template>

<style scoped>
.tree-item {
  margin: 2px 0;
}

.tree-node {
  padding: 4px 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.node-icon {
  width: 20px;
  text-align: center;
}

.node-name {
  flex: 1;
}

.tree-children {
  margin-left: 20px;
  display: none;
  border-left: 1px dotted #404040;
}

.tree-children-open {
  display: block;
}

.tree-node:hover {
  background-color: #383838;
}
</style>
